<?php

namespace App\Jobs;

use App\Models\Posts\WxPostsImg;
use App\Wen\Utils\ImageUtils;
use App\Wen\Utils\StrUtils;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Intervention\Image\Facades\Image;

class UpdatePostImgWHJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    public $tries = 1;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    protected $post_img_id = '';
    public function __construct($post_img_id)
    {
        $this->post_img_id = $post_img_id;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        if(!_empty_($this->post_img_id)){
            $postImgs = WxPostsImg::where([
                ['id','=', $this->post_img_id],
                ['width', '=', 0],
            ])->inRandomOrder()->limit(3)->get();
        }else{
            $postImgs = WxPostsImg::where('width', 0)->inRandomOrder()->limit(3)->get();
        }

        if($postImgs->isEmpty()){
            return;
        }
        $rows = [];
        $postImgs->map(function ($v, $k) use (&$rows){
            try {

                list($img_width, $img_height, $type, $attr) = getimagesize($v->img_url);
                if($img_width > 0 && $img_height > 0){
                    $v->width = $img_width;
                    $v->height = $img_height;
                    $v->save();
                    $rows[] = $v->id;
                    return $v;
                }

            }catch (\Exception $e){
                if($v->height == 400){
                    $v->width = 750;
                    $v->height = 400;
                    $v->save();
                    $rows[] = $v->id;
                }else{
                    $v->width = 0;
                    $v->height = 400;
                    $v->save();
                    $rows[] = $v->id;
                }

            }
        });
    }
}
